# !/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import json

import requests
from bottle import Bottle

from conn.MyLogs import MyLogs
from schedu.ScheduleDb import ScheduDb
from schedu.bean.Schedule import Schedule

schedu = Bottle()


# 定时任务业务
class ScheduleService:
    base_link_url = 'http://172.17.0.9:4002/job'
    # base_link_url = ''

    def __init__(self):
        ScheduDb.get_pool()

    @staticmethod
    def get_schedus(param):
        jobName = param['key']
        count_sql = f" SELECT count(`id`) FROM `schedu_data` WHERE 1=1 "
        fetch_sql = f" SELECT `id`,`jobName`,`jobGroupName`,`jobClass`,`triggerName`,`triggerGroupName`," \
                    f"`cronExpression`,`callBack`,`create_time` FROM `schedu_data` WHERE 1=1 %s "
        if len(jobName) > 0:
            fetch_sql = fetch_sql % f"AND jobName= \'{jobName}\'"
        else:
            fetch_sql = fetch_sql % ""

        int_begin = 0
        if param['pageNum'] > 1:
            int_begin = (param['pageNum'] - 1) * param['pageSize']
        elif param['pageNum'] == 1:
            int_begin = 0 * param['pageSize']
        fetch_sql = fetch_sql + f" ORDER BY `create_time` DESC LIMIT {int_begin}, {param['pageSize']}"
        try:
            data_total = ScheduDb.conn.sql_execute(count_sql)
            data_list = ScheduDb.conn.sql_fetch(fetch_sql)
            items = []
            if len(data_list) > 0:
                for data in data_list:
                    _url = ScheduleService.base_link_url + '/queryjobApi?jobName=%s' % data[1]
                    res = requests.get(url=_url)
                    if res.status_code == 200:
                        datas_json = json.loads(res.text)
                        if len(datas_json['data']) > 0:
                            jobTriggerName=str(data[4]).split("_")
                            if len(jobTriggerName) > 1:
                                job_TriggerName_pre = jobTriggerName[0]
                                job_TriggerName_post = jobTriggerName[1]
                            else:
                                job_TriggerName_pre = jobTriggerName[0]
                                job_TriggerName_post = ""
                            item = {"id": data[0], "jobName": data[1], 'jobGroupName': data[2], 'jobClass': data[3],
                                    'triggerName': job_TriggerName_pre, "triggerName_post": job_TriggerName_post,
                                    'triggerGroupName': data[5], "cronExpression": data[6], "callBack": data[7],
                                    "createTime": str(data[8]),
                                    "prevFireTime": datas_json['data'][0]['prevFireTime'],
                                    "nextFireTime": datas_json['data'][0]['nextFireTime'],
                                    "triggerState": datas_json['data'][0]['triggerState']}
                    else:
                        jobTriggerName = str(data[4]).split("_")
                        if len(jobTriggerName) > 1:
                            job_TriggerName_pre = jobTriggerName[0]
                            job_TriggerName_post = jobTriggerName[1]
                        else:
                            job_TriggerName_pre = jobTriggerName[0]
                            job_TriggerName_post = ""
                        item = {"id": data[0], "jobName": data[1], 'jobGroupName': data[2], 'jobClass': data[3],
                                'triggerName': job_TriggerName_pre, "triggerName_post": job_TriggerName_post,
                                'triggerGroupName': data[5], "cronExpression": data[6], "callBack": data[7],
                                "createTime": str(data[8]),
                                "prevFireTime": '',
                                "nextFireTime": '',
                                "triggerState": ''}
                    items.append(item)
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {'data': []}

    @staticmethod
    def info(id):
        fetch_sql = f" SELECT `id`,`jobName`,`jobGroupName`,`jobClass`,`triggerName`,`triggerGroupName`," \
                    f"`cronExpression`,`callBack`,`create_time` FROM `schedu_data` WHERE 1=1 %s " % f"AND id= {id}"
        try:
            item = {}
            data_list = ScheduDb.conn.sql_fetch(fetch_sql)
            if len(data_list) > 0:
                data = data_list[0]
                _url = ScheduleService.base_link_url + '/queryjobApi?jobName=%s' % data[1]
                res = requests.get(url=_url)
                datas_json = json.loads(res.text)
                if len(datas_json['data']) > 0:
                    jobTriggerName = str(data[4]).split("_")
                    if len(jobTriggerName) > 1:
                        job_TriggerName_pre = jobTriggerName[0]
                        job_TriggerName_post = jobTriggerName[1]
                    else:
                        job_TriggerName_pre = jobTriggerName[0]
                        job_TriggerName_post = ""
                    item = {"id": data[0], "jobName": data[1], 'jobGroupName': data[2], 'jobClass': data[3],
                            'triggerName': job_TriggerName_pre, "triggerName_post": job_TriggerName_post,
                            'triggerName': job_TriggerName_pre, "triggerName_post": job_TriggerName_post,
                            'triggerGroupName': data[5], "cronExpression": data[6], "callBack": data[7],
                            "createTime": str(data[8]),
                            "prevFireTime": datas_json['data'][0]['prevFireTime'],
                            "nextFireTime": datas_json['data'][0]['nextFireTime'],
                            "triggerState": datas_json['data'][0]['triggerState']}
            return {"code": 200, "data": item, "message": ""}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": item, "message": "数据读取异常"}

    @staticmethod
    def add_schedu(scheduData):
        try:
            check_sql = f"SELECT COUNT(1) FROM `schedu_data` WHERE `jobName` = \'{scheduData.job_name}\'"
            data_list = ScheduDb.conn.sql_fetch(check_sql)
            if data_list[0][0] == 0:
                now = datetime.datetime.now()
                execute_sql = f" INSERT INTO `schedu_data` (`jobName`, `jobGroupName`, `jobClass`, `triggerName`, `triggerGroupName`, `cronExpression`, `callBack`, `create_time`) " \
                              f" VALUES( \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')"
                execute_sql = execute_sql % (
                    scheduData.job_name, scheduData.job_group_name, scheduData.job_class, scheduData.trigger_name,
                    scheduData.trigger_group_name, scheduData.cron_expression, scheduData.call_back,
                    now.strftime('%Y-%m-%d %H:%M:%S'))
                ScheduDb.conn.sql_execute(execute_sql)
                return {"code": 200, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    @staticmethod
    def del_schedu(scheduData):
        execute_sql = f"DELETE FROM `schedu_data` WHERE jobName = \'{scheduData.job_name}\' "
        try:
            ScheduDb.conn.sql_commit(execute_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    @staticmethod
    def update_schedu(input_id, scheduData):
        try:
            check_sql = f"SELECT COUNT(1) FROM `schedu_data` WHERE `jobName` = \'{scheduData.job_name}\'"
            data_list = ScheduDb.conn.sql_fetch(check_sql)
            old_data_check = f"SELECT id FROM `schedu_data` WHERE `jobName` = \'{scheduData.job_name}\'"
            old_data = ScheduDb.conn.sql_fetch(old_data_check)
            if data_list[0][0] > 0 and old_data[0][0] == input_id:
                update_str = Schedule.split_params(scheduData)
                update_sql = "UPDATE `schedu_data` SET %s WHERE id= %d" % (update_str, input_id)
                ScheduDb.conn.sql_commit(update_sql)
                return {"code": 200, "data": None}
            else:
                return {"code": 500, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    @staticmethod
    def client_pause_schedu(param):
        _obj = {"jobName": param.job_name, "jobGroupName": param.job_group_name}
        res = requests.post(url=ScheduleService.base_link_url + '/pausejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据恢复成功")
            return {"code": 200, "data": None}
        else:
            MyLogs.logger.error("任务数据后台恢复失败，请检查服务端日志")
            return {"code": 500, "data": None}

    @staticmethod
    def client_resume_schedu(param):
        _obj = {"jobName": param.job_name, "jobGroupName": param.job_group_name}
        res = requests.post(url=ScheduleService.base_link_url + '/resumejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            return {"code": 200, "data": None}
        else:
            return {"code": 500, "data": None}

    @staticmethod
    def client_ref_schedu(param):
        _obj = {"jobName": param.job_name, "jobGroupName": param.job_group_name}
        res = requests.post(url=ScheduleService.base_link_url + '/refreshjob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据刷新成功")
            return {"code": 200, "data": None}
        else:
            MyLogs.logger.error("任务数据后台刷新失败，请检查服务端日志")
            return {"code": 500, "data": None}

    @staticmethod
    def client_push_schedu(schedule):
        _obj = {"jobName": schedule.job_name, "jobGroupName": schedule.job_group_name, "jobClass": schedule.job_class,
                "triggerName": schedule.trigger_name, "triggerGroupName": schedule.trigger_group_name,
                "cronExpression": schedule.cron_expression, "callBack": schedule.call_back}
        res = requests.post(url=ScheduleService.base_link_url + '/addjob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据添加成功")
            return {"code": 200, "data": None}
        else:
            MyLogs.logger.error("任务数据后台添加失败，请检查服务端日志")
            return {"code": 500, "data": None}

    @staticmethod
    def client_reset_schedu(schedule):
        _obj = {"jobName": schedule.job_name, "jobGroupName": schedule.job_group_name,
                "jobClass": schedule.job_class,
                "triggerName": schedule.trigger_name, "triggerGroupName": schedule.trigger_group_name,
                "cronExpression": schedule.cron_expression, "callBack": schedule.call_back}
        res = requests.post(url=ScheduleService.base_link_url + '/reschedulejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据更新成功")
            return {"code": 200, "data": None}
        else:
            MyLogs.logger.error("任务数据后台更新失败，请检查服务端日志")
            return {"code": 500, "data": None}

    @staticmethod
    def client_delete_schedu(schedule):
        _obj = {"jobName": schedule.job_name, "jobGroupName": schedule.job_group_name}
        res = requests.post(url=ScheduleService.base_link_url + '/deletejob', data=json.dumps(_obj),
                            headers={'Content-Type': 'application/json'})
        if res.status_code == 200:
            MyLogs.logger.info("定时任务数据删除成功")
            return {"code": 200, "data": None}
        else:
            MyLogs.logger.error("任务数据后台删除失败，请检查服务端日志")
            return {"code": 500, "data": None}

    @staticmethod
    def run_fun():
        print("123")
